import {createApp, ref} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//1.引入element-plus组件库与其样式
import ElementPlus, {ElMessage} from 'element-plus'
import 'element-plus/dist/index.css'
//2.引入element-plus图标库,并起别名为ElementPlusIconsVue
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//6.1修改elementPlus默认中文
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

//10.1 配置后端服务器的根路径
const BASE_URL = 'http://localhost:8080';
//window对象是浏览器内置的全局对象,给它设置的属性就是全局属性,可以在任意的script标签中使用!
window.BASE_URL = BASE_URL;


const app = createApp(App)/* 创建vue实例,并起名为app */

//10.2 给app(Vue对象)也设置后端的根路径,这样可以在任意的template标签中使用!
app.config.globalProperties.BASE_URL = BASE_URL;

// 添加全局用户状态响应
// app.config.globalProperties.$user = ref(null)

// 监听localStorage变化
// window.addEventListener('storage', () => {
//     const userData = localStorage.getItem('user')
//     app.config.globalProperties.$user.value = userData ? JSON.parse(userData) : null
// })



//3.将所有导入的图标组件变为键值对数组,并依次遍历取出每一个图标组件[key, component]
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    // 4.将当前遍历到的图标组件注册为当前vue实例的全局组件
    app.component(key, component)
}
//5.为前vue实例应用element-plus组件库
//6.2 app.use(ElementPlus,{ locale: zhCn })将El本地化为中文
app.use(ElementPlus,{ locale: zhCn }).use(store).use(router).mount('#app')

//7.解决ResizeObserver Error
const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    }
}
const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16);
        super(callback);
    }
}

//8.定义全局方法,获取当前登录的用户数据
window.getUser = () => {
    return localStorage.user ? JSON.parse(localStorage.user) : null ;
}

//9.配置路由守卫
//to 即将要去到的目标路由
//from 当前的路由
//next 是放行函数,调用next()才能进入到目标路由to

// router.beforeEach((to, from, next) => {
//     const user = localStorage.getItem('user')
//     const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
//
//     if ((to.path === '/login' || to.path === '/register') && user) {
//         ElMessage.error('请先登录')
//         next('/login')
//     } else if (!requiresAuth && user) {
//         next('/home')
//     } else {
//         next()
//     }
// })
router.beforeEach((to, from, next) => {
    //const user = localStorage.getItem('user')
    const token = localStorage.getItem('token');
    // 白名单路径
    const publicPaths = ['/login', '/register']

    if (!publicPaths.includes(to.path) && !token) {
        ElMessage.error('请先登录')
        next('/login')
    } else {
        next()
    }
})





